<template>
	<view>
		<view class="m-share">
			<image :src="current_img" mode=""></image>
		</view>
		<view class="m-btn" v-if="current_img" @click="downLoad">
			<text>保存图片</text>
			<image src="../static/down.png" mode=""></image>
		</view>
		 <canvas id="myCanvas"  canvas-id="myCanvas" class="myCanvas" :style="{width:canvasW+'px',height:canvasH+'px'}"></canvas>
	</view>
</template>

<script>
	import {get_userInfo} from "@/common/function/api_fun.js"
	export default {
		data() {
			return {
				canvasW:670,
				canvasH:871,
				userinfo:{},
				wxcode:'',
				current_img:'',
			}
		},
		onLoad() {
			uni.showLoading({
				title:'海报生成中'
			})
			get_userInfo((data)=>{
				this.userinfo = data
				this.getWxCode()
				
			})
			
		},
		methods: {
			async startDraw(score) {
				let {
					canvasW,
					canvasH,
				} = this
				let that = this
				//主图
				let main_img_obj = {
					path: '../static/sharebg.png',
					x: 0,
					y: 0,
					w: canvasW,
					h: canvasH,
					r: 0
				}

				//用户头像
				let user_avatar_obj = {
					src: this.userinfo.user_image,
					x: 270,
					y:22,
					r: 65
				}
				console.log('获取用户头像start')
				let {
					path: user_path
				} = await this.GetImageInfo(user_avatar_obj.src)
				console.log('获取用户头像end')
				user_avatar_obj.path = user_path
				
				//二维码
				let wxcode = this.wxcode
				console.log(wxcode)
				let qrcode_obj = {
					src: wxcode,
					x:135,
					y: 321,
					r: 200
				}
				console.log('获取二维码start')
				let {
					path: qrcode_path
				} = await this.GetImageInfo(qrcode_obj.src)
				console.log('获取二维码end')
				qrcode_obj.path = qrcode_path

				//用户名称
				let user_name = this.userinfo.name
				//手机号
				let promote_word = this.userinfo.username

				setTimeout(() => {
					const ctx = uni.createCanvasContext('myCanvas', this)
					ctx.beginPath()
					// ctx.setFillStyle('#fff');
					// ctx.fillRect(0, 0, canvasW, canvasH)
					//绘制主图
					this.roundRect(ctx,
						main_img_obj.x,
						main_img_obj.y,
						main_img_obj.w,
						main_img_obj.h,
						main_img_obj.r,
						main_img_obj.path)

					ctx.setTextBaseline('top')
					ctx.font = 'normal 34px sans-serif';
					let titleW = ctx.measureText(user_name).width
					ctx.setFillStyle('#34302D');
					ctx.fillText(user_name, (canvasW - titleW) / 2, 170)

					ctx.font = 'normal bold 24px sans-serif';
					let titleW2 = ctx.measureText(promote_word).width
					ctx.setFillStyle('#75706A');
					ctx.fillText(promote_word, (canvasW - titleW2) / 2, 212)
					ctx.save()
					ctx.restore()

					//绘制用户头像
					this.circular(ctx, user_avatar_obj.x, user_avatar_obj.y, user_avatar_obj.r, user_avatar_obj
						.path)
					
					//绘制二维码
					this.circular(ctx, qrcode_obj.x, qrcode_obj.y, qrcode_obj.r, qrcode_obj.path)
					ctx.draw(true, () => {
						setTimeout(() => {
							uni.hideLoading()
							this.exportCanvasPath()
						}, 1000)
					})
				})

			},
			getWxCode() {
				this.$http.getJson('users_shareInfo').then(res=>{
					if(res.code == 1){
						this.wxcode = res.data.code
						// this.wxcode = 'https://jitai.dx.hdapp.com.cn//upload/20240315/888_2024031506552639444.png'
						this.startDraw()
					}
				})
			},
			getTextWidthNum(text, num = 0, width, ctx) {
				let len = text.length
				for (let i = num; i < len; i++) {
					if (ctx.measureText(text.slice(0, i)).width >= width) {
						return i
					}
				}
				return len - 1
			},
			/**
			 * 文字省略 补...
			 * @str为原文字
			 * @num为第几个字开始补 ...
			 */
			textOverflow(text, max, res = false) {
				let arr = text.split('')
				let num = 0
				let str = ''
				arr.forEach((item, index) => {
					if (num < max) {
						str += String(item)
						if (item.match(/[\u4e00-\u9fa5]/g) || item.match(/[A-Z]/g)) {
							num += 1
						} else if (item.match(/[a-z]/g)) {
							num += 0.55
						} else if (item.match(/[(^\s*)|(\s*$)]/g)) {
							num += 0.2
						} else if (item.match(/[0-9]/g) || item.match(/[%&',;=?~$\x22]/g)) {
							num += 0.54
						}
					}
				})
				if (res) {
					return str
				}
				return num >= max ? str + '...' : str
			},
			textEllipsisIndex(text, max) {
				let arr = text.split('')
				let num = 0
				let i = 0
				arr.forEach((item, index) => {
					if (num < max) {
						if (item.match(/[\u4e00-\u9fa5]/g) || item.match(/[A-Z]/g)) {
							num += 1
						} else if (item.match(/[a-z]/g)) {
							num += 0.55
						} else if (item.match(/[(^\s*)|(\s*$)]/g)) {
							num += 0.2
						} else if (item.match(/[0-9]/g) || item.match(/[%&',;=?~$\x22]/g)) {
							num += 0.54
						}
						i = index
					}
				})
				return i
			},
			GetImageInfo(src) {
				return new Promise((resolve, reject) => {
					uni.getImageInfo({
						src,
						success(res) {
							resolve(res)
						},
						fail(error) {
							reject(error)
						}
					})
				})
			},
			/**
			 * 圆形
			 */
			circular(ctx, x, y, r, path) {
				ctx.save()
				ctx.beginPath() //开始创建一个路径
				ctx.setStrokeStyle('transparent')
				ctx.arc(x + r, y + r, r, 0, 2 * Math.PI, false) //画一个圆形裁剪区域
				ctx.stroke()
				ctx.clip() //裁剪
				ctx.drawImage(path, x, y, 2 * r, 2 * r) //绘制图片
				ctx.restore() //恢复之前保存的绘图上下文
			},
			/**
			 * 圆角矩形 
			 */
			roundRect(ctx, x, y, w, h, r, img) {
				ctx.save()
				// 开始绘制
				ctx.beginPath()
				// 因为边缘描边存在锯齿，最好指定使用 transparent 填充
				// 这里是使用 fill 还是 stroke都可以，二选一即可
				// ctx.setFillStyle('transparent')
				ctx.setStrokeStyle('transparent')
				// 左上角
				ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
				// border-top
				ctx.moveTo(x + r, y)
				ctx.lineTo(x + w - r, y)
				ctx.lineTo(x + w, y + r)
				// 右上角
				ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
				// border-right
				ctx.lineTo(x + w, y + h - r)
				ctx.lineTo(x + w - r, y + h)
				// 右下角
				ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
				// border-bottom
				ctx.lineTo(x + r, y + h)
				ctx.lineTo(x, y + h - r)
				// 左下角
				ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
				// border-left
				ctx.lineTo(x, y + r)
				ctx.lineTo(x + r, y)
				// 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应
				// ctx.fill()
				ctx.stroke()
				ctx.closePath()
				// 剪切
				ctx.clip()
				ctx.drawImage(img, x, y, w, h)
				ctx.restore() //恢复之前保存的绘图上下文
			},
			exportCanvasPath() {

				// console.log(canvasH,canvasW)
				uni.canvasToTempFilePath({
					canvasId: 'myCanvas',
					fileType: 'png',
					quality: 1,
					success: (res) => {
						console.log('导出图片',res.tempFilePath)
						this.current_img = res.tempFilePath
					},
					fail: (err) => {
						console.log(err);
					}
				})
			},
			downLoad() {
				let {
					current_img
				} = this
				if (current_img == '') {
					uni.showToast({
						icon: 'none',
						title: '海报绘制中，请稍等~'
					})
					return
				}
				uni.saveImageToPhotosAlbum({
					filePath: current_img,
					success() {
						// console.log('保存')
						uni.showToast({
							title: '图片保存成功'
						})
					}
				})
			}
		}

	}
</script>

<style lang="scss">
	page {
		min-height: 100vh;
		background: #FFF3E6;
	}
	.myCanvas{
		position: fixed;
		left: 1000px;
	}
	.m-share{
		width: 670rpx;
		height: 871rpx;
		margin: 80rpx auto 0;
		image{
			width: 100%;
			height: 100%;
		}
	}
	.m-btn{
		padding: 80rpx 0 0;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 34rpx;
		color: #34302D;
		image{
			width: 34rpx;
			height: 34rpx;
			margin-left: 8rpx;
		}
	}
</style>